package org.ciallo.simplemusicplayer.adapter;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.data.dao.PlayCountDao;
import org.ciallo.simplemusicplayer.data.model.Song;

import java.util.Locale;

/**
 * @author Jukomu
 * @Description:
 * @Package: org.ciallo.simplemusicplayer.adapter
 * @Project: SimpleMusicPlayer
 * @name: PlayStatsAdapter
 * @Date: 2025/6/13-07:53
 * @Filename: PlayStatsAdapter
 */
public class PlayStatsAdapter extends ListAdapter<PlayCountDao.SongWithPlayCount, PlayStatsAdapter.PlayStatsViewHolder> {

    private final OnSongClickListener songClickListener;

    public interface OnSongClickListener {
        void onSongClick(Song song, int position);
    }

    public PlayStatsAdapter(OnSongClickListener listener) {
        super(DIFF_CALLBACK);
        this.songClickListener = listener;
    }

    private static final DiffUtil.ItemCallback<PlayCountDao.SongWithPlayCount> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<PlayCountDao.SongWithPlayCount>() {
                @Override
                public boolean areItemsTheSame(@NonNull PlayCountDao.SongWithPlayCount oldItem, @NonNull PlayCountDao.SongWithPlayCount newItem) {
                    // Song 实体应该有一个可靠的唯一ID
                    if (oldItem.song == null || newItem.song == null) return false;
                    return oldItem.song.getId() == newItem.song.getId();
                }
                @Override
                public boolean areContentsTheSame(@NonNull PlayCountDao.SongWithPlayCount oldItem, @NonNull PlayCountDao.SongWithPlayCount newItem) {
                    if (oldItem.song == null || newItem.song == null) return false;
                    // 比较关键内容
                    return oldItem.song.equals(newItem.song) && oldItem.playCount == newItem.playCount;
                }
            };


    @NonNull
    @Override
    public PlayStatsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_song_play_stat, parent, false);
        return new PlayStatsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PlayStatsViewHolder holder, int position) {
        PlayCountDao.SongWithPlayCount item = getItem(position);
        if (item != null) {
            holder.bind(item, position, songClickListener);
        }
    }

    static class PlayStatsViewHolder extends RecyclerView.ViewHolder {
        TextView tvRank;
        ImageView ivCover;
        TextView tvTitle;
        TextView tvArtist;
        TextView tvPlayCount;

        PlayStatsViewHolder(View itemView) {
            super(itemView);
            tvRank = itemView.findViewById(R.id.textView_stat_rank);
            ivCover = itemView.findViewById(R.id.imageView_stat_cover); // <--- 初始化
            tvTitle = itemView.findViewById(R.id.textView_stat_song_title);
            tvArtist = itemView.findViewById(R.id.textView_stat_song_artist);
            tvPlayCount = itemView.findViewById(R.id.textView_stat_play_count);
        }

        void bind(final PlayCountDao.SongWithPlayCount item, int position, final OnSongClickListener listener) {
            if (item.song == null) return; // 防御性编程

            tvRank.setText(String.valueOf(position + 1));
            tvTitle.setText(item.song.getTitle());
            tvArtist.setText(item.song.getArtistName());
            tvPlayCount.setText(String.format(Locale.getDefault(), "%d次", item.playCount > 0 ? item.playCount : 0)); // 处理playCount为0或负数的情况

            // 使用 Glide 加载专辑封面
            Context context = itemView.getContext();
            Uri coverUri = null;
            if (item.song.getAlbumArtUri() != null && !item.song.getAlbumArtUri().isEmpty()) {
                try {
                    coverUri = Uri.parse(item.song.getAlbumArtUri());
                } catch (Exception e) {
                    // Log error if needed
                }
            }

            Glide.with(context)
                    .load(coverUri)
                    .placeholder(R.drawable.default_album_art) // 确保有默认图
                    .error(R.drawable.default_album_art)
                    .into(ivCover);

            itemView.setOnClickListener(v -> {
                if (listener != null) {
                    // 使用 getBindingAdapterPosition() 更安全
                    int currentPosition = getBindingAdapterPosition();
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        // 在回调中仍然传递 Song 对象
                        listener.onSongClick(item.song, currentPosition);
                    }
                }
            });
        }
    }
}
